<template>
  <div class="register-container" v-loading="loading" :element-loading-text="loadingText">
    <transition name="fade-slide" mode="out-in">
      <form @submit.prevent="handleRegister" class="register-form">
        <div class="form-group">
          <label for="register-phone">
            <i class="fas fa-mobile-alt"></i> 手机号
          </label>
          <div class="phone-input">
            <input id="register-phone" type="tel" v-model="registerForm.phone" placeholder="请输入手机号" required
              maxlength="11" @input="formatPhoneNumber">
            <button type="button" class="send-code-btn" :disabled="!canSendCode || isSendingCode"
              @click="sendVerificationCode">
              <span v-if="!isSendingCode">
                {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
              </span>
              <span v-else>
                <i class="fas fa-spinner fa-spin"></i> 发送中...
              </span>
            </button>
          </div>
          <div class="input-message">
            <i :class="'fas fa-check-circle'"></i>
            注册成功的初始密码为：123456789
          </div>
        </div>

        <div class="form-group">
          <label for="register-code">
            <i class="fas fa-sms"></i> 验证码
          </label>
          <div class="input-wrapper">
            <input id="register-code" type="text" v-model="registerForm.verificationCode" placeholder="请输入验证码" required
              maxlength="6">
          </div>
        </div>

        <div class="form-options">
          <label class="agree-terms">
            <input type="checkbox" v-model="registerForm.agreeTerms" required>
            我已阅读并同意 <a href="#">用户协议</a> 和 <a href="#">隐私政策</a>
          </label>
        </div>

        <button type="submit" class="submit-btn" :disabled="isRegistering || !canRegister">
          <span v-if="!isRegistering">
            <i class="fas fa-user-plus"></i> 注册
          </span>
          <span v-else>
            <i class="fas fa-spinner fa-spin"></i> 注册中...
          </span>
        </button>
      </form>
    </transition>
  </div>
</template>

<script>
import { sendCode as sendCodeAPI, enroll as enrollAPI, phoneAuth as phoneAuthAPI } from "@/api/user";

export default {
  name: 'RegisterView',
  data() {
    return {
      isRegistering: false,
      isSendingCode: false,
      isPhoneAvailable: false,
      phoneCheckMessage: '',
      countdown: 0,
      registerForm: {
        phone: '',
        verificationCode: '',
        agreeTerms: false
      },
      loginForm: {
        phone: '',
        password: '123456789',
        remember: false
      },
      loading: false,
      loadingText: '注册中'
    }
  },
  computed: {
    canSendCode() {
      return /^1[3-9]\d{9}$/.test(this.registerForm.phone) && this.countdown === 0
    },
    canRegister() {
      return (
        this.registerForm.phone &&
        this.registerForm.verificationCode &&
        this.registerForm.agreeTerms
      )
    }
  },
  methods: {
    formatPhoneNumber() {
      // 自动格式化手机号为数字
      this.registerForm.phone = this.registerForm.phone.replace(/\D/g, '')
    },
    checkPhoneAvailability() {
      if (!this.registerForm.phone || !/^1[3-9]\d{9}$/.test(this.registerForm.phone)) {
        this.phoneCheckMessage = ''
        return
      }

      // 模拟API检查
      setTimeout(() => {
        const isAvailable = Math.random() > 0.3
        this.isPhoneAvailable = isAvailable
        this.phoneCheckMessage = isAvailable
          ? '手机号可用'
          : '手机号已被注册'
      }, 500)
    },
    async sendVerificationCode() {
      if (!this.canSendCode) return

      this.isSendingCode = true
      setTimeout(async () => {
        this.isSendingCode = false
        this.countdown = 60
        const timer = setInterval(() => {
          this.countdown--
          if (this.countdown <= 0) {
            clearInterval(timer)
          }
        }, 1000)

        try {
          let params = {
            phone: this.registerForm.phone,
          };

          await sendCodeAPI(params);
          this.$message.success('验证码发送成功');
        } catch (error) {
          this.$message.error(error);
        }
      }, 1000)
    },
    async handleRegister() {
      if (!this.canRegister) return
      
      try {
        this.isRegistering = true
        this.loading = true;
        let res = await enrollAPI(this.registerForm);
        if (res != "") {
          let { data } = res.data;

          this.loginForm.phone = this.registerForm.phone

          // 登录完成后，登录账户
          this.loadingText = '正在自动登录请稍后';
          localStorage.setItem("token", data);
          this.$router.push("/index");
        }else{
          this.loading = true;
          this.isRegistering = false;
        }

        
      } catch (error) {
        this.loading = true;
        this.$message.error(error);
      }
    },
  },

  watch: {
    'registerForm.phone'(newVal) {
      if (/^1[3-9]\d{9}$/.test(newVal)) {
        this.checkPhoneAvailability()
      } else {
        this.phoneCheckMessage = ''
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import "@/styles/variables.less";

.register-container {
  width: 100%;
}

.form-group {
  margin-bottom: 20px;
  position: relative;

  label {
    display: block;
    margin-bottom: 8px;
    font-size: 14px;
    color: @gray-700;
    font-weight: 500;

    i {
      margin-right: 8px;
      color: @gray-500;
    }
  }

  input {
    width: 100%;
    padding: 12px 15px;
    border: 1px solid @gray-300;
    border-radius: 8px;
    font-size: 14px;
    transition: all 0.3s ease;
    background-color: @gray-50;
    height: 46px;
    box-sizing: border-box;

    &:focus {
      outline: none;
      border-color: @primary;
      box-shadow: 0 0 0 3px rgba(@primary, 0.1);
      background-color: white;
    }

    &::placeholder {
      color: @gray-400;
    }
  }

  .phone-input,
  .input-wrapper {
    position: relative;
    display: flex;
    height: 46px;
    width: 100%;
  }

  .phone-input {
    input {
      flex: 1;
      padding-right: 110px;
    }

    .send-code-btn {
      position: absolute;
      right: 5px;
      top: 50%;
      transform: translateY(-50%);
      height: calc(100% - 10px);
      padding: 0 10px;
      background: @primary;
      color: white;
      border: none;
      border-radius: 6px;
      font-size: 12px;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        background: darken(@primary, 5%);
      }

      &:disabled {
        background: @gray-400;
        cursor: not-allowed;
      }
    }
  }

  .input-wrapper {
    input {
      flex: 1;
      padding-right: 15px;
    }
  }

  .input-message {
    margin-top: 6px;
    font-size: 12px;
    display: flex;
    align-items: center;

    i {
      margin-right: 5px;
    }

    &.error {
      color: @danger;
    }

    &:not(.error) {
      color: @success;
    }
  }
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  font-size: 13px;

  .agree-terms {
    display: flex;
    align-items: center;
    color: @gray-600;

    input {
      margin-right: 8px;
    }

    a {
      color: @primary;
      text-decoration: none;

      &:hover {
        text-decoration: underline;
      }
    }
  }
}

.submit-btn {
  width: 100%;
  padding: 14px;
  background: @primary;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 20px;

  &:hover {
    background: darken(@primary, 5%);
    transform: translateY(-2px);
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  }

  &:disabled {
    background: @gray-400;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
  }

  i {
    margin-right: 8px;
  }
}

.fade-slide-enter-active,
.fade-slide-leave-active {
  transition: all 0.3s ease;
}

.fade-slide-enter,
.fade-slide-leave-to {
  opacity: 0;
  transform: translateY(10px);
}

@media (max-width: 768px) {
  .form-group {

    .phone-input,
    .input-wrapper {
      height: 42px;

      input {
        height: 42px;
        padding: 10px 12px;
      }

      .send-code-btn {
        font-size: 11px;
        padding: 0 8px;
      }
    }
  }
}
</style>